package com.bookstore.spring.service;
import com.bookstore.spring.dao.*;
import com.bookstore.spring.pojo.*;
import com.bookstore.spring.web.BookStoreWebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;

/**
 * Created by Admin on 2016/8/23.
 */
@Service
public class CashServiceImp implements CashService {
    @Autowired
    private UserMap userMap;
    @Autowired
    private BookMap bookMap;
    @Autowired
    private AccountMap accountMap;
    @Autowired
    private TradeMap tradeMap;
    @Autowired
    private TradeItemMap tradeItemMap;

    /**
     * 表单验证
     *
     * @param username
     * @param accountId
     * @return
     */
    public StringBuffer validateFormField(String username, String accountId) {
        StringBuffer error = new StringBuffer();
        if (username == null || username.trim().equals("")) {
            error.append("用户名不能为空!<br>");
        }
        if (accountId == null || accountId.trim().equals("")) {
            error.append("用户帐号不能为空!");
        }
        return error;
    }

    public StringBuffer validateUser(String username, String accountId) {
        StringBuffer error = new StringBuffer();
        boolean flag = false;
        User user = userMap.getUserByName(username);
        if (user != null) {
            int account = user.getAccountId();
            if (accountId.equals("" + account)) {
                flag = true;
            }
        }
        if (!flag) {
            error.append("用户名和帐号不匹配!");
        }
        return error;
    }

    public StringBuffer validateStoreNumber(HttpServletRequest request) {
        StringBuffer error = new StringBuffer();
        ShoppingCart cart = BookStoreWebUtils.getShoppingCart(request);
        for (ShoppingCartItem sci : cart.getItems()) {
            int quantity = sci.getQuantity();
            int storeNumber = bookMap.getBook(sci.getBook().getId()).getStoreNumber();
            if (quantity > storeNumber) {
                error.append(sci.getBook().getTitle() + "库存不足!");
            }
        }
        return error;
    }

    public StringBuffer validateBalance(HttpServletRequest request, String accountId) {
        StringBuffer error = new StringBuffer();
        ShoppingCart cart = BookStoreWebUtils.getShoppingCart(request);
        Account account = accountMap.get(Integer.parseInt(accountId));
        if (cart.getTotalMoney() > account.getBalance()) {
            error.append("余额不足!");
        }
        return error;
    }


    public void cash(ShoppingCart shoppingCart, String username, String accountId) {
        //1. 更新 mybooks 数据表相关记录的 salesamount 和 storenumber
        bookMap.batchUpdateStoreNumberAndSalesAmount(shoppingCart.getItems());
        //      int i=10/0;
        //2. 更新 account 数据表的 balance
        accountMap.updateBalance(Integer.parseInt(accountId), (int) shoppingCart.getTotalMoney());
        //3. 向 trade 数据表插入一条记录
        Trade trade = new Trade();
        trade.setUserId(userMap.getUserByName(username).getUserId());
        trade.setTradeTime(new Date(new Date().getTime()));
        tradeMap.insert(trade);
        System.out.println(trade.getTradeId());
        //4. 向 tradeitem 数据表插入 n 条记录
        Collection<TradeItem> items = new ArrayList<>();
        for (ShoppingCartItem sci : shoppingCart.getItems()) {
            TradeItem tradeItem = new TradeItem();
            tradeItem.setBookId(sci.getBook().getId());
            tradeItem.setQuantity(sci.getQuantity());
            tradeItem.setTradeId(trade.getTradeId());
            items.add(tradeItem);
        }
        tradeItemMap.batchSave(items);
        //5. 清空购物车
        shoppingCart.clear();
    }

    public UserMap getUserMap() {
        return userMap;
    }

    public void setUserMap(UserMap userMap) {
        this.userMap = userMap;
    }

    public BookMap getBookMap() {
        return bookMap;
    }

    public void setBookMap(BookMap bookMap) {
        this.bookMap = bookMap;
    }

    public AccountMap getAccountMap() {
        return accountMap;
    }

    public void setAccountMap(AccountMap accountMap) {
        this.accountMap = accountMap;
    }

    public TradeMap getTradeMap() {
        return tradeMap;
    }

    public void setTradeMap(TradeMap tradeMap) {
        this.tradeMap = tradeMap;
    }

    public TradeItemMap getTradeItemMap() {
        return tradeItemMap;
    }

    public void setTradeItemMap(TradeItemMap tradeItemMap) {
        this.tradeItemMap = tradeItemMap;
    }
}
